import type { IProduct, IChapter, IComment, IEpisode } from '@/typings/interface';
import { getDetail, getChapterList, getCommentPage, getMeterial } from '@/api/video';
import navigateTo from '@/utils/navigator';
import type { IPage } from '@/typings/api';
import { isFreeEpisode } from '@/utils';

export const useVideo = defineStore('video', () => {
  // 课程信息
  let videoInfo = $ref<IProduct>();
  // 课程章集
  let videoChapterList = $ref<IChapter[]>([]);
  let currentEpisodeId = $ref<number>(-1);
  let commentPage = $ref<IPage<IComment>>();
  const { isLogin } = $(useUser());

  // 集标题
  const currentEpisodeTitle = $computed(() => {
    return videoChapterList.flatMap((c) => c.episodeList).filter((e) => e.id === currentEpisodeId)[0]?.title ?? '出现错误，找不到标题';
  });

  // 获取视频详情信息
  async function init(videoId: number) {
    // 获取课程详情
    const { data: _videoInfo } = await getDetail(videoId);
    videoInfo = _videoInfo;
    // 获取章集
    const { data: _videoChapterList } = await getChapterList(videoId);
    videoChapterList = _videoChapterList;
    // 获取评论
    const { data: _commentPage } = await getCommentPage({
      page: 1,
      size: 10,
      id: videoId
    });
    commentPage = _commentPage;
    // 课程资料获取
    if (isLogin) {
      const { data: _meterial } = await getMeterial(videoId);
      videoInfo = {
        ...videoInfo,
        note_url: _meterial?.note_url,
        bd_zip_url: _meterial?.bd_zip_url,
        ali_zip_url: _meterial?.ali_zip_url
      };
    }
  }
  // 跳转到详情页
  async function toDetail(videoId: number) {
    navigateTo(`/pages/detail/index?id=${videoId}`);
    await init(videoId);
  }

  // 切换集
  function changeEpisodeId(eid: number) {
    currentEpisodeId = eid;
  }

  // 跳转播放页面方法
  async function toPlayer(episode: Pick<IEpisode, 'free' | 'id'>, productId?: number) {
    if (await isFreeEpisode({ free: episode.free, product_id: productId ?? videoInfo?.id ?? 1 })) {
      currentEpisodeId = episode.id;
      navigateTo(`/pages/player/index?id=${productId ?? videoInfo?.id}&eid=${episode.id}`, { isNeedLogin: true });
    }
  }

  // 自动播放切换集+集是否可观看
  async function nextEpisode() {
    let _episode: IEpisode | undefined;
    let needNextEpisode = false; // 判断该集是否为某章的最后一集
    // 不存在集id时停止
    if (currentEpisodeId === -1) return false;
    try {
      videoChapterList.forEach((chapter, index) => {
        // 章无更多集则自动跳转下一章播放
        if (needNextEpisode) {
          _episode = videoChapterList[index].episodeList[0];
          // 成功跳转下一章则停止循环
          throw new Error('We got episode.');
        }
        chapter.episodeList.forEach((episode, idx) => {
          if (episode.id === currentEpisodeId) {
            // 判断是不是该章的最后一集，如果不是则自动切换
            if (idx + 1 < chapter.episodeList.length) _episode = chapter.episodeList[idx + 1];
            else needNextEpisode = true;
          }
        });
      });
    } catch (ignore) {}

    // 播放最后一集则结束
    if (!_episode) return false;

    // 判断该集是否免费
    if (!(await isFreeEpisode(_episode))) return false;

    // 更改pinia里的集id
    currentEpisodeId = _episode.id;
    return true;
  }
  return $$({
    videoInfo,
    init,
    toDetail,
    videoChapterList,
    currentEpisodeId,
    currentEpisodeTitle,
    changeEpisodeId,
    commentPage,
    toPlayer,
    nextEpisode
  });
});
